<template>
  <PageWrapper>
    <a-card>
      <div style="margin-bottom: 20px; padding: 20px">
        <a-form :model="formState">
          <a-row :gutter="[20, 20]">
            <a-col :xs="24" :sm="6">
              <a-form-item :label="t('sys.analysis.columns.mac')">
                <a-input
                  allowClear
                  :placeholder="t('sys.configuration.pleaseenter') + t('sys.analysis.columns.mac')"
                  v-model:value="formState.mac"
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="6">
              <a-space>
                <a-button @click="handleSearch" :icon="h(SearchOutlined)" type="primary">
                  {{ t('sys.form.placeholder.inquire') }}
                </a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-table
        @change="handleTableChange"
        :pagination="pagination"
        :loading="loading"
        bordered
        rowKey="id"
        :showExpandColumn="false"
        :columns="deviceLogColumns"
        :dataSource="deviceLogDataSource"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'action'">
            <a-button @click="detailsClick(record)" type="link">
              {{ t('sys.device.columns.log') }}
            </a-button>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 详情模态框 -->
    <a-modal
      v-model:visible="ModalShow"
      :title="t('sys.device.columns.log')"
      :width="900"
      :footer="null"
    >
      <a-table
        :loading="deviceLogFilePathLoading"
        :pagination="deviceLogFilePathPagination"
        :columns="deviceLogFilePathColumns"
        :dataSource="deviceLogFilePathList"
        @change="handleDeviceLogFilePathChange"
        bordered
        rowKey="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'fileLogPath'">
            <a-button @click="handleFileDownload(record)" type="link">
              {{ record.fileLogPath }}
            </a-button>
          </template>
        </template>
      </a-table>
    </a-modal>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref, onMounted, h, UnwrapRef, Ref } from 'vue';
  import { SearchOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import { queryDeviceLogFilePathList, queryDeviceLogFileList } from '@/api/demo/device';
  import { PageWrapper } from '@/components/Page';
  import { taskLogColumns, taskErrorColumns, taskSeverColumns } from './account.data';
  import { useI18n } from '@/hooks/web/useI18n';

  const { t } = useI18n();
  const activeKey = ref('1');
  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
  });
  const handleSearch = () => {
    init();
  };
  const handleTableChange = (e) => {
    pagination.value = e;
    init();
  };
  const deleteCick = () => {
    console.log(selectedRowKeyslist.value);
  };
  const deleteAllCick = () => {};
  const selectedRowKeyslist: Ref<UnwrapRef<(string | number)[]>> = ref<(string | number)[]>([]);
  const rowSelection = ref({
    checkStrictly: false,
    onChange: (selectedRowKeys: (string | number)[], selectedRows: any) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      selectedRowKeyslist.value = selectedRowKeys;
    },
    onSelect: (record: any, selected: boolean, selectedRows: any) => {
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected: boolean, selectedRows: any, changeRows: any) => {
      console.log(selected, selectedRows, changeRows);
    },
  });
  const ModalShow = ref(false);
  const detailsRecord = ref({});
  const deviceLogFilePathList = ref([]);
  const deviceLogFilePathPagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
  });
  const deviceLogFilePathLoading = ref(false);

  const detailsClick = (record) => {
    ModalShow.value = true;
    detailsRecord.value = record;
    // 如果是设备日志，加载文件路径列表
    loadDeviceLogFilePathList();
  };

  const loadDeviceLogFilePathList = () => {
    deviceLogFilePathLoading.value = true;
    queryDeviceLogFilePathList({
      current: deviceLogFilePathPagination.value.current,
      size: deviceLogFilePathPagination.value.pageSize,
      deviceFileLogId: detailsRecord.value?.id || '',
    })
      .then((res) => {
        if (res.code == 200) {
          deviceLogFilePathList.value = res.data.records || [];
          deviceLogFilePathPagination.value.total = res.data.total || 0;
        }
        deviceLogFilePathLoading.value = false;
      })
      .catch(() => {
        deviceLogFilePathLoading.value = false;
      });
  };

  const handleDeviceLogFilePathChange = (pagination) => {
    deviceLogFilePathPagination.value = { ...deviceLogFilePathPagination.value, ...pagination };
    loadDeviceLogFilePathList();
  };

  // 处理文件下载
  const handleFileDownload = (record) => {
    if (record.fileLogPath) {
      // 创建下载链接
      const a = document.createElement('a');
      a.href = record.fileLogPath;
      // 指定文件名（若后端返回的Content-Disposition已设置文件名，可省略）
      // 模拟点击
      document.body.appendChild(a);
      a.click();
      // 移除元素，避免DOM冗余
      document.body.removeChild(a);
    }
  };
  const errorTypeList = ref([
    {
      title: '脚本错误',
      value: '1',
    },
    {
      title: '任务错误',
      value: '2',
    },
    {
      title: '设备错误',
      value: '3',
    },
    {
      title: '系统错误',
      value: '4',
    },
  ]);
  const formState = ref({});
  const statusSelectList = ref([
    {
      title: '正常',
      value: '1',
    },
    {
      title: '异常',
      value: '2',
    },
  ]);
  const taskLogdataSource = ref([
    {
      id: 1,
      name: 'fasdfiennskf12321',
      logType: '设备名1',
      remark: '推特',
      status: 1,
      end_time: '2025-11-1',
      cread_time: '2025-11-1',
    },
    {
      id: 2,
      name: 'fasdfiennskf12321',
      logType: '设备名1',
      remark: '推特',
      status: 0,
      end_time: '2025-11-1',
      cread_time: '2025-11-1',
    },
    {
      id: 3,
      name: 'fasdfiennskf12321',
      logType: '设备名1',
      remark: '推特',
      status: 2,
      end_time: '2025-11-1',
      cread_time: '2025-11-1',
    },
  ]);
  const taskSeverdataSource = ref([
    {
      id: 1,
      name: 'fasdfiennskf12321',
      deiveName: '设备名1',
      versions: '1.2',
      status: 1,
      reamk: '推特',
      end_time: '2025-11-1',
      cread_time: '2025-11-1',
    },
    {
      id: 4,
      name: 'fasdfiennskf12321',
      deiveName: '设备名1',
      versions: '1.2',
      status: 1,
      reamk: '斗鱼',
      end_time: '2025-11-1',
      cread_time: '2025-11-1',
    },
    {
      id: 3,
      name: 'fasdfiennskf12321',
      deiveName: '设备名1',
      versions: '1.2',
      status: 1,
      reamk: '百度',
      end_time: '2025-11-1',
      cread_time: '2025-11-1',
    },
    {
      id: 2,
      name: 'fasdfiennskf12321',
      deiveName: '设备名1',
      versions: '1.2',
      status: 1,
      reamk: '谷歌',
      end_time: '2025-11-1',
      cread_time: '2025-11-1',
    },
  ]);
  const deviceLogColumns = ref([
    { title: '日志ID', dataIndex: 'id', key: 'id' },
    { title: 'MAC地址', dataIndex: 'mac', key: 'mac' },
    { title: '时间', dataIndex: 'createTime', key: 'createTime' },
    { title: '操作', dataIndex: 'action', key: 'action' },
  ]);

  // 设备日志文件路径列定义
  const deviceLogFilePathColumns = ref([
    { title: '文件ID', dataIndex: 'id', key: 'id' },
    {
      title: '文件路径',
      dataIndex: 'fileLogPath',
      key: 'fileLogPath',
    },
  ]);
  const deviceLogDataSource = ref([]);
  const taskErrordataSource = ref([
    {
      id: 1,
      name: 'fasdfiennskf12321',
      logType: '脚本错误',
      message: '脚本版本过低,请升级脚本',
      status: 1,
      end_time: '2025-11-1',
      cread_time: '2025-11-1',
    },
    {
      id: 2,
      name: 'fasdfiennskf12321',
      logType: '任务强制中断',
      message: '用户强制关闭',
      status: 1,
      end_time: '2025-11-1',
      cread_time: '2025-11-1',
    },
    {
      id: 3,
      name: 'fasdfiennskf12321',
      logType: '任务强制中断',
      message: '用户强制重启',
      status: 1,
      end_time: '2025-11-1',
      cread_time: '2025-11-1',
    },
  ]);
  const loading = ref(true);
  const init = () => {
    loading.value = true;
    queryDeviceLogFileList({
      current: pagination.value.current,
      size: pagination.value.pageSize,
    })
      .then((res) => {
        if (res.code == 200) {
          deviceLogDataSource.value = res.data.records || [];
          pagination.value.total = res.data.total || 0;
        }
        loading.value = false;
      })
      .catch(() => {
        loading.value = false;
      });
  };
  onMounted(() => {
    init();
  });
</script>
<style scoped lang="scss">
  .status-label {
    width: 100px;
  }
</style>
